'''
Created on 20/02/2012

@author: Bruna
'''
import serial

class SerialController():
    '''
    Controls the serial port used to communicate with Arduino 
    '''

    def __init__(self, main_controller, port_name="COM3", baud_rate=9600):
        '''
        Constructor
        '''
        self.main_controller = main_controller
        self.port = None
        self.port_name = port_name
        self.baud_rate = baud_rate
        
    def connect(self):
        '''
        Opens port and send a command to connect 
        '''
        self.port = serial.Serial(self.port_name, self.baud_rate)
        self.port.write('A')
        
    def disconnect(self):
        '''
        Sends a command to disconnect 
        '''
        self.port.write('X')
        self.port = None
    
    def readln(self):
        '''
        Reads a line from serial port
        
        @return: line read
        '''
        return self.port.readline()
        
        
    def change_speed(self, speed):
        '''
        Sends a command to change motor speed
        
        @param speed: new speed
        @raise ValueError: raises an error if trying to change to a invalid speed value 
        '''
        if (0 <= speed <= 3):
            self.port.write('S' + str(speed))
        else:
            raise ValueError("Cannot change speed to " + speed)